import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore,combineReducers } from 'redux'
import {addTodo} from './actions'
import App from './components/App'
import './index.css'

const initialState = [
	{text: 'initialState', id: 1, completed: false}
];

//reducer specify how the application's state changes
//注意默认情况下返回state
//不直接修改state
//对state不同字段的修改,写成不同的函数,不需要知道完整的state是什么样的
//Now we can rewrite the main reducer as a function that calls the reducers managing parts of the state, and combines them into a single object. It also doesn’t need to know the complete initial state anymore. 
function todos(state = initialState, action) {
	switch (action.type) {
		case 'ADD':
			return [
					{
						id: state.reduce((maxId, todo) => Math.max(maxId,todo.id), -1) + 1,
						text: action.text,
						completed: false,
					},
					...state
				]
		case 'DELETE':
			return state.filter(todo => todo.id !== action.id)
		case 'TOGGLE':
			return state.map(todo => todo.id === action.id ?
				Object.assign({}, todo, {completed: !todo.completed}) : todo
			)
		case 'EDIT':
			return state.map(todo => todo.id === action.id ?
				Object.assign({}, todo, {text: action.text}) : todo
			)
		default:
			return state;
	}
}

function visibilityFilter(state = 'SHOW_ALL', action) {
	switch (action.type) {
		case 'SET_VISIBILITY_FILTER':
			return action.filter
		default:
			return state
	}
}

const rootReducer = combineReducers({
	visibilityFilter,
	todos
});

let store = createStore(rootReducer)

let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
)

// Dispatch some actions
store.dispatch(addTodo('Learn about actions'))

//unsubscribe();

//store.dispatch(addTodo('after unsubscribe'))

/*
 * Note that this is completely equivalent to:
 *
 * export default function todoApp(state = {}, action) {
	  return {
		visibilityFilter: visibilityFilter(state.visibilityFilter, action),
		todos: todos(state.todos, action)
	  }
	}
 *
 */

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
